<template>
	<div class="id-card-reader">
		<el-card header="身份证信息读取" class="main-card">
			<!-- 设备控制区域 -->
			<div class="control-panel">
				<div class="control-buttons">
					<el-button type="success" @click="readIDCard" :disabled="!isconncet" size="large" class="read-btn">
						<template #icon>
							<el-icon>
								<Reading />
							</el-icon>
						</template>
						读取身份证
					</el-button>

					<el-button type="warning" @click="closeConnect" :disabled="!isconncet" size="large">
						<template #icon>
							<el-icon>
								<Close />
							</el-icon>
						</template>
						断开连接
					</el-button>
				</div>
			</div>

			<!-- 连接信息 -->
			<div v-if="isconncet" class="connection-info">
				<el-result icon="success" title="设备连接成功" sub-title="身份证读卡器已就绪，请点击'读取身份证'按钮开始读取">
					<template #extra>
						<el-tag type="success" size="large">已连接</el-tag>
						<el-tag type="info" size="large" style="margin-left: 10px;">就绪</el-tag>
					</template>
				</el-result>
			</div>


			<!-- 身份证信息显示 -->
			<div v-if="idCardInfo" class="id-card-info">
				<el-divider content-position="left">身份证信息</el-divider>
				<el-row :gutter="20">
					<el-col :span="8">
						<div class="photo-section">
							<div class="photo-title">证件照片</div>
							<div class="photo-container">
								<img :src="idCardInfo.photo" alt="身份证照片" class="id-photo"
									v-if="idCardInfo.photo && idCardInfo.photo !== '未知'" />
								<div v-else class="no-photo">
									<el-icon>
										<Picture />
									</el-icon>
									<span>无照片数据</span>
								</div>
							</div>
						</div>
					</el-col>
					<el-col :span="16">
						<div class="info-section">
							<el-descriptions title="基本信息" border :column="1">
								<el-descriptions-item label="姓名">
									<el-tag type="primary" size="large">{{ idCardInfo.name }}</el-tag>
								</el-descriptions-item>
								<el-descriptions-item label="性别">
									<el-tag :type="idCardInfo.gender === '男' ? 'success' : 'danger'" size="large">
										{{ idCardInfo.gender }}
									</el-tag>
								</el-descriptions-item>
								<el-descriptions-item label="民族">{{ idCardInfo.nation }}</el-descriptions-item>
								<el-descriptions-item label="出生日期">{{ idCardInfo.birth }}</el-descriptions-item>
								<el-descriptions-item label="身份证号">
									<el-text type="primary" size="large" style="font-family: monospace;">
										{{ idCardInfo.idNumber }}
									</el-text>
								</el-descriptions-item>
								<el-descriptions-item label="住址">
									<el-text>{{ idCardInfo.address }}</el-text>
								</el-descriptions-item>
								<el-descriptions-item
									label="签发机关">{{ idCardInfo.issuingAuthority }}</el-descriptions-item>
								<el-descriptions-item label="有效期限">{{ idCardInfo.validPeriod }}</el-descriptions-item>
							</el-descriptions>
						</div>
					</el-col>
				</el-row>
			</div>

			<!-- 常见问题 -->
			<div class="faq-section" style="margin-top: 30px;">
				<el-collapse>
					<el-collapse-item title="常见问题解答">
						<div class="faq-content">
							<h4>1. 为什么看不到设备选择窗口？</h4>
							<p>请确保：</p>
							<ul>
								<li>使用 Chrome 89+ 或 Edge 89+ 浏览器</li>
								<li>网站具有串口访问权限（浏览器地址栏旁边会有串口图标）</li>
								<li>身份证读卡器已正确连接到电脑</li>
								<li>设备驱动程序已正确安装</li>
							</ul>

							<h4>2. 连接设备时提示"未选择任何设备"？</h4>
							<p>这是因为在选择设备时点击了"取消"或关闭了选择窗口。请重新点击"连接身份证读卡器"按钮，并在弹出的设备选择窗口中选择您的身份证读卡器。</p>

							<h4>3. 如何确认设备已正确连接？</h4>
							<p>在Windows系统中，可以在"设备管理器"中查看"端口(COM和LPT)"项，确认身份证读卡器对应的COM端口。</p>

							<h4>4. 读取身份证没有反应？</h4>
							<p>请检查：</p>
							<ul>
								<li>身份证是否正确放置在读卡器上</li>
								<li>读卡器指示灯是否正常</li>
								<li>设备连接是否稳定</li>
								<li>尝试重新连接设备</li>
							</ul>
						</div>
					</el-collapse-item>
				</el-collapse>
			</div>
		</el-card>
	</div>
</template>

<script>
	import {
		Close,
		Connection,
		Delete,
		DocumentAdd,
		Picture,
		Reading,
		Refresh
	} from '@element-plus/icons-vue';

	export default {
		name: 'IDCardReader',
		components: {
			Connection,
			Reading,
			Close,
			Picture,
			DocumentAdd,
			Refresh,
			Delete
		},
		data() {
			return {
				idCardInfo: {},
				isconncet: false,
				websockets: '',
				statusArr: [{
						state: 0,
						value: '正在连接'
					},
					{
						state: 1,
						value: '已建立连接'
					},
					{
						state: 2,
						value: '正在关闭连接'
					},
					{
						state: 3,
						value: '已关闭连接'
					},
				]
			}
		},
		mounted() {
			this.ocrRecognition();

		},
		methods: {
			ocrRecognition() {
				if (!this.isconncet) {
					const url = "ws:127.0.0.1:9001"
					this.websockets = new WebSocket(url);
					// 2.监听websocket的状态变化，接收的信息，关闭时的状态

					//监听连接状态的变化
					this.websockets.onopen = (event) => this.socketChange();

					//监听接收消息的情况
					this.websockets.onmessage = (res) => {
						if (res.data === "failed to obtain ID card information") {
							console.log('获取身份证信息失败')
							return;
						}
						if (res.data === '连接设备失败') {

							this.closeConnect();
							return;
						}

						const alldata = res.data.split("|");
						console.log('alldata', alldata)
						if (alldata.length >= 17) {
							this.idCardInfo.name = alldata[3];
							this.idCardInfo.gender = alldata[4];
							this.idCardInfo.nation = alldata[5];
							this.idCardInfo.address = alldata[7];
							this.idCardInfo.birth = alldata[6];
							this.idCardInfo.idNumber = alldata[8];
							this.idCardInfo.issuingAuthority = alldata[9];
							this.idCardInfo.validPeriod = alldata[10] + "-" + alldata[11];
							if (alldata.length >= 21) {
								// 100U生成正反面
								this.idCardInfo.photo = 'data:image/jpeg;base64,' + alldata[20];
							}
						} else {

							console.log(res.data)
						}
					}
					//监听关闭时的状态变化
					this.websockets.onclose = (event) => this.socketChange();
				} else {
					console.log("设备断开");
					this.closeConnect();
				}
			},
			socketChange() {
				let state = this.websockets.readyState;
				console.log('state', state)

				//读身份证
				if (1 === state) {
					this.isconncet = true;
				}
				if (3 === state) {
					this.isconncet = false;
				}
			},
			closeConnect() {
				this.websockets.close();
			},
			readIDCard() {
				if (!this.isconncet) {
					console.log('未连接服务')
				} else {
					const parameterAll = "timeout=" + 10000;
					let val = "03?" + parameterAll;
					this.websockets.send(val);
				}
			}

		}
	}
</script>

<style scoped>
	.id-card-reader {
		padding: 20px;
		max-width: 1200px;
		margin: 0 auto;
	}

	.main-card {
		min-height: 600px;
	}

	.control-panel {
		margin-bottom: 20px;
	}

	.control-buttons {
		display: flex;
		gap: 10px;
		justify-content: center;
		margin-bottom: 20px;
	}

	.connect-btn,
	.read-btn {
		min-width: 180px;
	}

	.authorized-devices {
		margin-top: 20px;
	}

	.devices-list {
		padding: 10px;
	}

	.device-radio {
		display: block;
		margin-bottom: 10px;
		padding: 10px;
		border: 1px solid #e0e0e0;
		border-radius: 4px;
		transition: all 0.3s;
	}

	.device-radio:hover {
		border-color: #409eff;
		background-color: #f5f7fa;
	}

	.device-radio:deep(.el-radio__label) {
		display: block;
		width: 100%;
	}

	.device-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.device-name {
		font-weight: 500;
	}

	.device-status {
		font-size: 12px;
		padding: 2px 8px;
		border-radius: 10px;
		background-color: #f4f4f5;
		color: #909399;
	}

	.device-status.connected {
		background-color: #f0f9ff;
		color: #409eff;
	}

	.connection-info {
		margin: 20px 0;
	}

	.reading-guide {
		margin: 20px 0;
	}

	.photo-section {
		text-align: center;
		padding: 20px;
	}

	.photo-title {
		font-weight: bold;
		margin-bottom: 15px;
		color: #606266;
		font-size: 16px;
	}

	.photo-container {
		border: 2px dashed #e0e0e0;
		border-radius: 8px;
		padding: 20px;
		background: #fafafa;
	}

	.id-photo {
		width: 100%;
		max-width: 200px;
		height: auto;
		border-radius: 4px;
	}

	.no-photo {
		width: 200px;
		height: 250px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #909399;
	}

	.no-photo .el-icon {
		font-size: 48px;
		margin-bottom: 10px;
	}

	.info-section {
		padding: 10px 0;
	}

	.action-buttons {
		text-align: center;
		margin-top: 30px;
		display: flex;
		gap: 15px;
		justify-content: center;
	}

	.faq-content h4 {
		color: #409eff;
		margin: 15px 0 10px 0;
	}

	.faq-content ul {
		margin: 10px 0;
		padding-left: 20px;
	}

	.faq-content li {
		margin-bottom: 5px;
	}
</style>